import json

from django.shortcuts import render
from .models import Teacher
from django.http import HttpResponse

# Create your views here.

# 如何实现前端参数的接收   自动传入 request 请求对象   参数
#  querystring   /add?name=tom    post  formdata

"""
 #  获取请求方式   GET  POST  DELETE  PUT
    method = request.method
    print(f'method: {method}')
    # 获取请求路径
    path = request.path
    print(f'path: {path}')
    #  name   get  参数必传  抛出异常
    # name = request.GET['name']
    # 获取请求参数  name  default='admin'  设置默认值
    # name1 = request.GET.get('name',default='admin')
    # print(f'name: {name1}')
    # name2 = request.POST.get('name')
    # print(f'name: {name2}')

    #  add?hb=music&hb=movie&hb=book
    # hb_list = request.GET.getlist('hb')
    # print(hb_list)

    # 接收json格式的数据
    data_dict = request.body.decode('utf-8')
    print(f'data_dict: {data_dict}')

"""


def teacher_add(request):
    # 接收json格式的数据
    teacher = request.body.decode('utf-8')
    teacher_obj = json.loads(teacher)
    print(f'teacher: {teacher}', type(teacher_obj))
    # 保存数据
    Teacher.objects.create(**teacher_obj)

    return HttpResponse('ok', content_type='text/html; charset=utf-8')


def teacher_delete(request):
    id = request.GET.get('id')
    # 删除数据
    Teacher.objects.filter(id=id).delete()
    return HttpResponse('ok', content_type='text/html; charset=utf-8')


def teacher_update(request):
    #  name  id
    teacher = request.body.decode('utf-8')
    teacher_obj = json.loads(teacher)
    Teacher.objects.filter(id=teacher_obj['id']).update(name=teacher_obj['name'])
    return HttpResponse('ok', content_type='text/html; charset=utf-8')


def teacher_list(request):
    pass


def teacher_one(request):
    id = request.GET.get('id')
    teacher = Teacher.objects.filter(id=id).first()
    print(teacher)
    return HttpResponse('ok', content_type='text/html; charset=utf-8')
